package com.example.news2.app;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.widget.FrameLayout;
import android.widget.RadioGroup;

import com.example.news2.R;
import com.example.news2.base.BaseFragment;
import com.example.news2.home.fragment.HomeFragment;
import com.example.news2.shoppingcart.fragment.ShoppingCartFragment;

import java.util.ArrayList;

public class MainActivity extends FragmentActivity {
    FrameLayout frameLayout;
    RadioGroup rgMain;
    //管理fragments
    private ArrayList<BaseFragment> fragsList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        frameLayout=(FrameLayout)findViewById(R.id.frameLayout);
        rgMain=(RadioGroup)findViewById(R.id.rg_main);
        initFragments();
        initListener();
    }
    /*按顺序加载碎片，确保位置的正确性*/
    private void initFragments(){
        fragsList=new ArrayList<>();
        fragsList.add(new HomeFragment());//0
        fragsList.add(new ShoppingCartFragment());//1
    }

    public void initListener(){

        rgMain.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.rb_home:
                        switchFragment(getFragment(0));
                        break;
                    case R.id.rb_cart:
                        switchFragment(getFragment(1));
                        break;
                    default:
                        break;
                }
            }
        });
        //设置默认显示首页（通过模拟点击首页导航）
        rgMain.check(R.id.rb_home);
    }
    private void switchFragment(BaseFragment nextFragment) {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.frameLayout,nextFragment).commit();//通过事务提交的方式

    }
    private BaseFragment getFragment(int position) {
        if (fragsList != null && fragsList.size() > 0) {
            BaseFragment baseFragment = fragsList.get(position);
            return baseFragment;
        }
        return null;
    }

}